package com.shxy.controller;

import com.alibaba.fastjson.JSONObject;
import com.shxy.common.ApiResult;
import com.shxy.entity.Retiree;
import com.shxy.service.IRetireeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/v2/retiree")
public class RetireeController {
    @Autowired
    private IRetireeService retireeService;

    @GetMapping("/list")
    public ApiResult list(@RequestParam(name = "page", defaultValue = "1", required = false) int page,
                          @RequestParam(name = "size", defaultValue = "10", required = false) int size) {
        // 1、获取分页的列表
        Page<Retiree> pagedList = retireeService.list(page, size);
        // 2、格式转换
        List<JSONObject> list = convertToItems(pagedList.getContent());

        return ApiResult.success(list);
    }

    /**
     * 列表转换
     * @param list
     * @return
     */
    private List<JSONObject> convertToItems(List<Retiree> list) {
        return list.stream().map(retiree -> {
            return convertToItem(retiree);
        }).collect(Collectors.toList());
    }

    /**
     * 对象转换
     * @param retiree
     * @return
     */
    private JSONObject convertToItem(Retiree retiree) {
        JSONObject jo = new JSONObject();
        jo.put("id", retiree.getId());
        jo.put("name", retiree.getName());
        jo.put("sex", retiree.getSex());
        jo.put("policital", retiree.getPolitical());
        jo.put("timeRetire", retiree.getTimeRetire());
        jo.put("identity", retiree.getIdentity());
        return jo;
    }
}
